package com.coderxq.blog.web.contoller;

import cn.hutool.core.lang.Console;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.coderxq.blog.annotation.LogAnnotation;
import com.coderxq.blog.exception.WsException;
import com.coderxq.blog.utils.ResponseResult;
import com.coderxq.blog.utils.jwt.JwtUtil;

import com.coderxq.blog.web.entity.dto.LoginDto;
import com.coderxq.blog.web.entity.dto.UserRoleParam;
import com.coderxq.blog.web.entity.pojo.User;
import com.coderxq.blog.web.entity.pojo.UserRoleMenu;
import com.coderxq.blog.web.entity.vo.UserInfo;
import com.coderxq.blog.web.service.user.UserService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.java.Log;
import okhttp3.Request;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @Author: lijingming
 * @Date: 2025/1/16
 * @Description:
 **/
@RestController
@RequestMapping("/User")
@Api(tags = "用户管理")
public class UserApi {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserApi.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @LogAnnotation("用户/获取用户方法")
    @GetMapping("/getUser/{id}")
    public String getUser(@PathVariable("id") Integer id){
        return "getUser";
    }


    @LogAnnotation("用户登录")
    @PostMapping("/login")
    public ResponseResult Login(@RequestBody LoginDto loginDto){
       UserInfo userInfo=  userService.getUserByAccount(loginDto.getAccount());

        if(userInfo==null){
            throw new WsException("用户不存在");
        }
        String Token =JwtUtil.createToken("coderxq","123456");
        Map resultInfo=new HashMap<String,Object>();

        resultInfo.put("data",userInfo);
        resultInfo.put("token",Token);

        return ResponseResult.okData(resultInfo);
    }

    @LogAnnotation("获取验证码")
    @GetMapping("/getVerificationCode/{phoneNum}")
    public Map getVerificationCode(@PathVariable("phoneNum") Long phoneNum){
        Map successMap=new HashMap<String,Object>();
        try{
            redisTemplate.opsForValue().set(Long.toString(phoneNum),  "123456", 5, TimeUnit.MINUTES);
            successMap.put("code",200);
            successMap.put("msg","发送成功");
            successMap.put("data","123456");
        }catch (Exception e){
            logger.error("error:",e);
            throw new WsException(e.getCause().getMessage());
        }
        return successMap;
    }


    @LogAnnotation("用户注册")
    @PostMapping("/registerUser")
    public String RegisterUser(@RequestBody User user){
      Integer count=  userService.insertUser(user);
        Map successMap=new HashMap<String,Object>();
        successMap.put("code",200);
        successMap.put("msg","注册成功");
        successMap.put("data",count.toString());
      return JSONUtil.toJsonStr(successMap);
    }

    @LogAnnotation("获取所有用户")
    @GetMapping("/getAllUserData")
    public ResponseResult getAllUserData(@RequestParam int pageNum,@RequestParam int pageSize){
        PageInfo<User> userList=  userService.getAllUser(pageNum,pageSize);

        return ResponseResult.okData(userList);
    }

    @LogAnnotation("根据用户id获取用户信息")
    @GetMapping("/getUserByUserId/{userId}")
    public ResponseResult getUserByUserId(@PathVariable("userId") String userId){
        UserInfo userinfo=  userService.getUserByUserId(userId);
        return ResponseResult.okData(userinfo);
    }




    @LogAnnotation("编辑用户")
    @PostMapping("/updateUser")
    public ResponseResult updateUser(@RequestBody UserInfo userinfo){
        userService.updateUser(userinfo);
        return ResponseResult.okMsg("成功");
    }




    @LogAnnotation("发送邮件")
    @PostMapping("/sendEmail")
    public String sendEmail(@RequestBody User user){
        Map successMap=new HashMap<String,Object>();
        try{
        String content = new String(Files.readAllBytes(Paths.get("D:\\新建文件夹 (2)\\test.html")), StandardCharsets.UTF_8);
        MailUtil.send("2628526932@qq.com", "摸鱼警告", content, true);

            successMap.put("code",200);
            successMap.put("msg","发送成功");
            successMap.put("data","");
        }catch (Exception e){
            logger.error("error:",e);
            throw new WsException(e.getCause().getMessage());
        }
        return JSONUtil.toJsonStr(successMap);
    }

    @LogAnnotation("新增用户角色")
    @PostMapping("/insertUserRole")
    public String insertUserRole(@RequestBody UserRoleParam insertUserRoleParam){
        Map successMap=new HashMap<String,Object>();
        try{
            Integer count=  userService.insertUserRole(insertUserRoleParam);
            successMap.put("code",200);
            successMap.put("msg","发送成功");
            successMap.put("data",count.toString());
        }catch (Exception e){
            logger.error("error:",e);
            throw new WsException(e.getCause().getMessage());
        }
        return JSONUtil.toJsonStr(successMap);
    }

    @LogAnnotation("获取用户对应角色所有菜单")
    @GetMapping("/getUserRoleMenu")
    public String getUserRoleMenu(@RequestParam String userId){
        ResponseResult successMap=new ResponseResult();
        try{
            UserRoleMenu userRoleMenu=  userService.getUserRoleMenu(userId);

            successMap= ResponseResult.okData(userRoleMenu);
        }catch (Exception e){
            logger.error("error:",e);
            throw new WsException(e.getCause().getMessage());
        }
        return JSONUtil.toJsonStr(successMap);
    }

}
